<template>
	<view :class="['chat_wraper', { 'small': isSmallScreen }]">
		<div class="loading" v-if="isLoading">Loading...</div>
			<z-paging 
			class="chat_room" 
			ref="chatRoom" 
			v-model="dataList"
			:auto="false"
			:fixed="false"
			:autoAdjustPositionWhenChat="false"
			:chat-loading-more-default-as-loading="false"
			:to-bottom-loading-more-enabled="false"
			@query="queryList"
			@scroll="scrollHandler"
			:refresher-only="!isSmallScreen"
			@scrolltoupper="onRefresh"
			:default-page-size="params.page_size"
			:use-chat-record-mode="isSmallScreen">
			
				<view :class="['chat_item', {'mine': item.sender == 'you'}]" v-for="(item,index) in dataList" :key="index" :id="`chat_${item.msg_id}`">
					<view class="chat_main">
						<view class="item_avatar" v-if="item.sender != 'you'">
							<image class="avatar_img" :src="item.sender == 'you' ? userInfo.avatar : '/static/img/evil-avatar.png'"></image>
						</view>
						<view class="item_main">
							<view class="item_content">
								<div class="item_name" v-if="item.sender != 'you'">The Defeated One</div>
								<view class="item_msg" v-if="item.sender == 'bot'" :id="`item_${item.msg_id}`">
									<view class="loading_text" v-if="item.loadingText">
										<view class="dot"></view>
										<view class="dot"></view>
										<view class="dot"></view>
									</view>
									
									<view 
									v-for="(itm, index) in item.msgList"
									class="item_text" 
									>
										<rich-text 
										:nodes="utils.removeMarkdownTags(itm)" 
										></rich-text>
									</view>
								</view>
								<view class="item_msg" :id="`item_${item.msg_id}`" v-else>
									<rich-text class="item_text" :nodes="item.message"></rich-text>
								</view>
							</view>
						</view>
					</view>
				</view>
					<template v-slot:empty>
					<view class="empty">
						<view class="empty_main">
							<image class="empty_icon" src="../../static/img/prayer.svg"></image>
							<view class="empty_title">
								Empty
							</view>
						</view>
					</view>
				</template>
			</z-paging>
	</view>
</template>

<script setup>
import { constants } from '@/config/index.js';
import { computed, reactive, ref, watch, getCurrentInstance, onMounted, nextTick } from 'vue';
import { onShow, onHide } from "@dcloudio/uni-app";
import { utils, storage,  } from '@/utils/index.js';
import { useWebSocketStore } from '@/store/index.js';
import apis from '@/apis/apis';

const { proxy } = getCurrentInstance();
const socketStore = useWebSocketStore();
const userInfo = computed(() => loginStore().userInfo);

const props = defineProps({
	isLoadRefresh: {
		type: Boolean,
		default: false
	},
	msg: {
		type: String,
		 default: ''
	}
}); 

const params = reactive({
	cuid: Number(userInfo.value?.cuid),
	page: 1,
	scenario_id: 10005,
	page_size: 20
});

const total = ref(0);
const chatRoom = ref();
const dataList = ref([]);
const isWriteing = ref(false);    // 实时消息，正在写入的状态...
// 定义响应式的变量来存储当前的媒体查询状态
const isSmallScreen = computed(() => loginStore().isSmallScreen);

const queryList = (pageNo, pageSize, from) => {
	// params.page = props.isLoadRefresh ? pageNo - 1 : pageNo;
	params.page = pageNo;
	
	socketStore.getHistory(params).then(data => {
		const { data: res } = data;

		if(!res.code) {
			let d = socketStore.historyMsgHandler(res.data.message_list);
			let lastId = '';
			
			if (!isSmallScreen.value) {
				d = d.reverse();
				lastId = dataList.value?.length > 0 ? `chat_${dataList.value[0].msg_id}` : '';
				d = [].concat(d, dataList.value)
			}
			
			total.value = res.data.total;
			chatRoom.value.complete(d).then((result) => {
				console.log(result);
				if (!isSmallScreen.value) {
					if (params.page == 1) {
						chatRoom.value.scrollToBottom(false);
					} else {
						uni.createSelectorQuery()
						.select(`#${lastId}`)  // 选择目标元素的 id 或 class
						.boundingClientRect((rect) => {
							chatRoom.value.scrollIntoViewByNodeTop(rect.top - 227)
							console.log(rect.top - 227);  // 获取到 top 值
						})
						.exec();
						
						// chatRoom.value.scrollIntoViewById(lastId);
					}
				}
			});
			
			isLoading.value = false;
		}
	}).catch(res => {
		chatRoom.value.complete(false);
	});
}

const reload = () => {
	chatRoom.value.reload();
}

const scrollData = ref(null);
const scrollHandler = (e) => {
	if (!isSmallScreen.value) {
		scrollData.value = e.detail;
		
		const bottom = scrollData.value?.scrollHeight - scrollData.value?.scrollTop;
		
		if(bottom > 550) {
			isScroll.value = true;
		} else {
			isScroll.value= false;
		}
	}
}

const isLoading = ref(false);
const onRefresh = () => {
	if (!isLoading.value && params.page < total.value && !isSmallScreen.value) {
		isLoading.value = true;
		
		const page = params.page + 1;
		queryList(page)
	}
}

watch(() => socketStore.botMsg, msg => {
	if (msg) {
		isWriteing.value = true;
		
		if (!isSmallScreen.value) {
			dataHandler(msg);
			// let d = dataList.value;
			 
			// d = [].concat(d, msg);
			// chatRoom.value.complete(d);
			// chatRoom.value.scrollToBottom(true);
		} else {
			chatRoom.value.addChatRecordData(msg, false, false);
		}
	} else {
		isWriteing.value = false;
		isScroll.value = false;
	}
})
let count = 0;
let top = 0;
watch(() => socketStore.botMsg, (val) => {
	count++;
	const bottom = top - scrollData.value?.scrollTop;

	if (val && !isSmallScreen.value && count % 4 == 0 && !isScroll.value && bottom < 300) {
		
		chatRoom.value.scrollToBottom(true);
	}
	
	uni.createSelectorQuery()
	.select(`.zp-paging-container`)  // 选择目标元素的 id 或 class
	.boundingClientRect((rect) => {
		top = Math.abs(rect.top) + 300;
	})
	.exec();
}, {
	deep: true
});
let isScroll = ref(false);
watch(() => props.msg, val => {
	if(val) {
		if (!isSmallScreen.value) {
			dataHandler(socketStore.socketMsgHandler(val));
		} else {
			chatRoom.value.addChatRecordData(socketStore.socketMsgHandler(val), false, false);
		}
		
		const par = {
			scenario_id: 10005,
		};
		
		socketStore.sendMsg(val, par);
		
		const bottom = scrollData.value?.scrollHeight - scrollData.value?.scrollTop;
		
		chatRoom.value.scrollToBottom(false);
	}
});

const dataHandler = (d, flag = true) => {
	if (flag) {
		dataList.value = [].concat(dataList.value, d);
	}
}

defineExpose({
	reload,
	isWriteing
})
</script>

<style lang="scss" scoped>
.chat_wraper {
	position: relative;
	display: flex;
	flex-direction: column;
	height: 100%;
	
	.loading {
		font-size: 32upx;
		color: #bbb;
		text-align: center;
		letter-spacing: 5upx;
	}
	
	.chat_room {
		position: relative;
		z-index: 99;
		flex: 1;
		overflow-y: auto;
		// background: url('../../static/img/bg.jpg') repeat-y;
		background-size: cover;
		// color: var(--text-color);
	}
	
	// .bg_none {
	// 	color: var(--b-white)!important;
	// 	background: transparent;
	// }
	
	// .bg_prayer {
	// 	color: var(--b-white)!important;
	// 	background: url('../../static/img/prayer.png') repeat-y;
	// 	background-size: cover;
	// }
	
	.chat_item {
		display: flex;
		flex-direction: column;
		// transform: scaleY(-1);
		color: #DDC090;
		font-size: 24upx;
		font-style: normal;
		font-weight: 500;
		line-height: 28upx;
		
		.chat_main {
			display: flex;
		}
		
		.item_avatar {
			width: 80upx;
			height: 80upx;
			border: 2px solid #fff;
			flex-shrink: 0;
			border-radius: 100%;
			
			.avatar_img {
				width: 100%;
				height: 100%;
				border-radius: 100%;
			}
		}
		
		.item_name {
			color: #DDC090;
			font-size: 24px;
			font-style: normal;
			font-weight: 800;
			line-height: normal;
			margin-bottom: 10upx;
		}
		
		.item_msg {
			user-select: text;
		}
		
		.item_content {
			padding: 0 20upx;
			word-break: break-all;
			border-radius: 20upx;
			
			
			.item_text {
				padding-bottom: 20upx;
				
				:deep(div) {
					font-size: 48upx;
					line-height: 56upx;
					font-weight: 400;
					padding: 10upx 0;
					word-break: break-word
				}
				
				:deep(h1) {
					font-size: 36upx;
				}
				
				:deep(h2) {
					font-size: 34upx;
				}
				
				:deep(h3) {
					font-size: 32upx;
				}
				
				:deep(h4, h5, h6) {
					font-size: 30upx;
				}
				
				:deep(.books-btn) {
					color: var(--text-color-hight);
				}
				
				&.selected {
					color: var(--text-color-hight);
				}
			}
		}
		
		.loading_text {
			display: flex;
			align-items: center;
			height: 54upx;
		}
		 
		.dot {
			display: inline-block;
			width: 16upx;
			height: 16upx;
			border-radius: 50%;
			background-color: var(--text-color-base);
			margin: 0 10upx;
			opacity: 0.8;
			animation: blink 1.4s ease infinite; /* 设置动画名称和时长等 */
		}
		 
		/* 第一个点延迟开始动画 */
		.dot:nth-child(1) {
			animation-delay: 0.1s;
		}
		 
		/* 第二个点稍微晚一些开始动画 */
		.dot:nth-child(2) {
			animation-delay: 0.2s;
		}
		 
		/* 第三个点再稍微晚一些开始动画 */
		.dot:nth-child(3) {
			animation-delay: 0.3s;
		}
		 
		@keyframes blink {
			0% {
				transform: scale(1);
				opacity: 0.8;
			}
			50% {
				transform: scale(1.2);
				opacity: 0.3;
			}
			100% {
				transform: scale(1);
				opacity: 0.8;
			}
		}
		
		.creat_card {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 40upx;
			
			.card_btn {
				display: flex;
				align-items: center;
				padding: 24upx 32upx;
				font-size: 28upx;
				font-weight: 400;
				line-height: 28upx;
			}
			
			.card_icon {
				width: 44upx;
				height: 44upx;
				margin-right: 12upx;
			}
		}
	}
	
	.mine {
		flex-direction: row-reverse;
		padding-bottom: 0;
		margin: 20upx 0;
		color: #fff;
		
		.item_avatar {
			padding: 0 0 0 10upx;
		}
			
		.item_content {
			padding: 10upx;
			margin-bottom: 0;
		}
	}

	.empty {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
		
		.empty_bg {
			width: 40%;
			height: 400upx;
			// background: url("../../static/img/banaba_bg.png") no-repeat;
			// background-size: contain;
		}
		
		.empty_main {
			text-align: center;
			
			.empty_icon {
				width: 176upx;
				height: 256upx;
				opacity: .3;
			}
			
			.empty_title {
				font-size: 32upx;
				font-weight: 600;
				margin: 40upx 0;
			}
			
			.empty_desc {
				font-size: 28upx;
				font-weight: 300;
				line-height: 42upx;
			}
			
			.empty_btn {
				font-size: 32upx;
				font-weight: 600;
				margin-top: 60upx;
			}
		}
	}
	
	.chat_bottom {
		position: relative;
	}
	
	.scroll_bottom {
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		top: -100upx;
		width: 100%;
		
		.scroll_bottom_icon {
			width: 64upx;
			height: 64upx;
		}
	}
	
	.chat_footer {
		position: relative;
	}
	
	.safeArea {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
}

@media (max-width: 1024px) {
	.chat_wraper .chat_item {
		.item_avatar {
			width: 48upx;
			height: 48upx;
			border: 2upx solid #fff;
		}
		.item_name {
			font-size: 32upx;
			line-height: 38upx;
		}
		
		.item_content .item_text {
			padding-bottom: 10upx;
			:deep(div) {
				font-size: 32upx;
				line-height: 38upx;
			}
		}
	}
	
	.small {
		.chat_item {
			transform: scaleY(-1);
		}
	}
}
</style>